package org.fight.net;

import org.fight.net.handler.KcpHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 *
 */
public class UdpServer {

    private int port;

    final NioEventLoopGroup group = new NioEventLoopGroup();

    public UdpServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        try {
            final Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.SO_BACKLOG, 128)  
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024)// 设置UDP读缓冲区为1M  
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024)// 设置UDP写缓冲区为1M  
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        public void initChannel(final NioDatagramChannel ch) throws Exception {

                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new KcpHandler());
                        }
                    });

            b.bind(port).sync();
        } finally {
            System.out.print("In Server Finally");
        }
    }

    public void shutdown() {
        group.shutdownGracefully();
        System.out.println("UDP Server Stop Success!");
    }
}
